import requests
from lxml import etree
import time
import asyncio
import aiohttp
from functools import lru_cache

# 创建一个全局session以复用连接
session = None

# 使用缓存避免重复请求相同数据
@lru_cache(maxsize=128)
def fetch_exponent_data_cached(pid, cid):
    return fetch_exponent_data(pid, cid)

async def fetch_exponent_data_async(pid, cid):
    start_time = time.time()  # 记录开始时间
    
    # mid页面
    url = f'https://vip.titan007.com/count/goalCount.aspx?t=1&sid={pid}&cid={cid}&l=0'

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.97 Safari/537.36',
    }
    
    global session
    if session is None:
        connector = aiohttp.TCPConnector(limit=100, ttl_dns_cache=300)
        session = aiohttp.ClientSession(connector=connector)
    
    try:
        # 异步发送请求
        async with session.get(url, headers=headers) as response:
            # 设置编码格式为GBK
            text = await response.text()
            response.encoding = 'gbk'

            # 处理结果
            html_tree = etree.HTML(text)
            
            # 主队
            mteam_texts = html_tree.xpath('/html/body/table[@class="font13"][1]/tbody/tr[4]/td[2]//text()')
            # 盘口
            dopen_texts = html_tree.xpath('/html/body/table[@class="font13"][1]/tbody/tr[4]/td[3]//text()')
            # 客队
            vteam_texts = html_tree.xpath('/html/body/table[@class="font13"][1]/tbody/tr[4]/td[4]//text()')
            # 主队2
            mteam2_texts = html_tree.xpath('/html/body/table[@class="font13"][1]/tbody/tr[5]/td[2]//text()')
            # 盘口2
            dopen2_texts = html_tree.xpath('/html/body/table[@class="font13"][1]/tbody/tr[5]/td[3]//text()')
            # 客队2
            vteam2_texts = html_tree.xpath('/html/body/table[@class="font13"][1]/tbody/tr[5]/td[4]//text()')

            result = [
                convert_list_to_string(mteam_texts),
                convert_list_to_string(dopen_texts),
                convert_list_to_string(vteam_texts),
                convert_list_to_string(mteam2_texts),
                convert_list_to_string(dopen2_texts),
                convert_list_to_string(vteam2_texts)
                ]
            
            end_time = time.time()  # 记录结束时间
            elapsed_time = end_time - start_time  # 计算运行时间
            print(f"fetch_exponent_data 运行时间: {elapsed_time:.4f} 秒")  # 打印运行时间
            
            return result
    except Exception as e:
        print(f"请求出错: {e}")
        return ["", ""]

def convert_list_to_string(list_data):
    # 使用join方法优化字符串拼接
    return " ".join(list_data)

def fetch_exponent_data(pid, cid):
    start_time = time.time()  # 记录开始时间
    
    # mid页面
    url = f'https://vip.titan007.com/count/goalCount.aspx?t=1&sid={pid}&cid={cid}&l=0'

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.97 Safari/537.36',
    }
    
    # 使用Session复用连接
    with requests.Session() as s:
        # 发送请求
        response = s.get(url, headers=headers)
        # 设置编码格式为GBK
        response.encoding = 'gbk'

        # 处理结果
        html_tree = etree.HTML(response.text)
        
        # 主队
        mteam_texts = html_tree.xpath('/html/body/table[@class="font13"][1]/tbody/tr[4]/td[2]//text()')
        # 盘口
        dopen_texts = html_tree.xpath('/html/body/table[@class="font13"][1]/tbody/tr[4]/td[3]//text()')
        # 客队
        vteam_texts = html_tree.xpath('/html/body/table[@class="font13"][1]/tbody/tr[4]/td[4]//text()')
        # 主队2
        mteam2_texts = html_tree.xpath('/html/body/table[@class="font13"][1]/tbody/tr[5]/td[2]//text()')
        # 盘口2
        dopen2_texts = html_tree.xpath('/html/body/table[@class="font13"][1]/tbody/tr[5]/td[3]//text()')
        # 客队2
        vteam2_texts = html_tree.xpath('/html/body/table[@class="font13"][1]/tbody/tr[5]/td[4]//text()')

        result = [
            convert_list_to_string(mteam_texts),
            convert_list_to_string(dopen_texts),
            convert_list_to_string(vteam_texts),
            convert_list_to_string(mteam2_texts),
            convert_list_to_string(dopen2_texts),
            convert_list_to_string(vteam2_texts)
            ]
        
        end_time = time.time()  # 记录结束时间
        elapsed_time = end_time - start_time   # 计算运行时间
        print(f"fetch_exponent_data 运行时间: {elapsed_time:.4f} 秒")  # 打印运行时间
        
        return result

# 提供一个关闭session的方法
async def close_session():
    global session
    if session:
        await session.close()

if __name__ == '__main__':
    pid = 2818546
    cid = 3
    result = fetch_exponent_data(pid, cid)
    print(result)